package com.example.demo.testdemo;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
/**
 * <p> 延时消息demo
 * 比如电商里，提交了一个订单就可以发送一个延时消息，1小时后去检查这个订单的状态，如果还是未付款就取消订单释放库存，经常遇到下单后会提醒15分钟内付款，超出时间未付款就自动取消订单
 * </p>
 *
 * @author Jon
 * @since 2021/7/14 11:15
 */
public class ScheduledMessageProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("producer_delay_order_group");
        producer.setNamesrvAddr("127.0.0.1:9876");
        producer.start();
        for (int i = 0; i < 10; i++) {
            Message message = new Message("topic_delay_order","tags","key"+i,"delay".getBytes(RemotingHelper.DEFAULT_CHARSET));
            //设置发送延时时间
           // 现在RocketMq并不支持任意时间的延时，需要设置几个固定的延时等级，从1s到2h分别对应着等级1到18
           //   private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
            message.setDelayTimeLevel(2);
            //发送消息
            SendResult result = producer.send(message);
            //发送状态
            System.out.println(result.getSendStatus());
        }
        producer.shutdown();

    }
}
